import React, {
    PropTypes,
    Component
} from 'react';

import {
    connect
} from 'react-redux';

require('../../css/index.css');
import {
    addTodo,
    completedTodo,
    removeTodo,
    toggleAllTodo,
    setVisibilityFilter,
    VisibilityFilters
} from '../actions/TodoAction';

import Header from '../components/Header';
import Footer from '../components/Footer';
import TodoList from '../components/TodoList';

class App extends Component {

    render() {
        const {
            dispatch,
            visibleTodos,
            totalCount,
            visibilityFilter
        } = this.props;

        return (
            <div className="todoapp">
                <Header title="todos" onKeyEnter={text=>dispatch(addTodo(text))}/>
                <section className="main">
                    <input type="checkbox" onChange={(e)=>dispatch(toggleAllTodo(e.nativeEvent.target.checked))} className="toggle-all"/>
                    <TodoList visibleTodos={visibleTodos} 
                    onToggleClick={(todoId) => dispatch(completedTodo(todoId))}
                    onRemoveClick={(todoId) => dispatch(removeTodo(todoId))}/>
                </section>
                <Footer visibilityFilter={visibilityFilter} visibleTodosCount={totalCount} onChangeFilter={(nextFilter)=>dispatch(setVisibilityFilter(nextFilter))}/>
            </div>
        );
    }

}

function filterTodos(todos, filter) {
    switch (filter) {
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter((todo) => todo.completed)
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter((todo) => !todo.completed)
        default:
            return todos;
    }
}

function select(state) {
    return {
        visibleTodos: filterTodos(state.todos, state.visibilityFilter),
        visibilityFilter: state.visibilityFilter,
        totalCount: state.todos.length
    };
}

export default connect(select)(App);